CODE 108. Swap Nodes in Pairs

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/11/04/2013-11-04-CODE 108 Swap Nodes in Pairs/

访问原文「CODE 108. Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public ListNode swapPairs(ListNode head) {
// Start typing your Java solution below
// DO NOT write main() function
ListNode newHead = new ListNode(0);
ListNode tmpHead = newHead;
ListNode tmp = head;
while (null != tmp && null != tmp.next) {
ListNode first = tmp;
ListNode second = tmp.next;
tmp = second.next;
tmpHead.next = second;
tmpHead.next.next = first;
tmpHead = tmpHead.next.next;
}
if (null != tmp) {
tmpHead.next = tmp;
tmpHead = tmpHead.next;
}
tmpHead.next = null;
return newHead.next;
}
Jerky Lu wechat
欢迎加入微信公众号